package com.uzykj.modules.blog.web;

import com.google.common.collect.Lists;
import com.uzykj.common.config.Global;
import com.uzykj.common.json.AjaxJson;
import com.uzykj.common.json.EditorJson;
import com.uzykj.common.utils.DateUtils;
import com.uzykj.common.utils.FileUtils;
import com.uzykj.common.utils.StringUtils;
import com.uzykj.common.utils.excel.ExportExcel;
import com.uzykj.common.utils.excel.ImportExcel;
import com.uzykj.core.persistence.Page;
import com.uzykj.core.web.BaseController;
import com.uzykj.modules.blog.entity.BlogNote;
import com.uzykj.modules.blog.service.BlogNoteService;
import com.uzykj.modules.sys.entity.User;
import com.uzykj.modules.sys.security.SystemAuthorizingRealm;
import com.uzykj.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author ghostxbh
 * @date 2020/7/9
 * 博客文章Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/blog/note")
public class BlogNoteController extends BaseController {

    @Autowired
    private BlogNoteService blogNoteService;

    @ModelAttribute
    public BlogNote get(@RequestParam(required = false) String id) {
        BlogNote entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = blogNoteService.get(id);
        }
        if (entity == null) {
            entity = new BlogNote();
        }
        return entity;
    }

    /**
     * 文章列表页面
     */
    @RequiresPermissions("blog:note:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/blog/note/blogNoteList";
    }

    /**
     * 文章列表数据
     */
    @ResponseBody
    @RequiresPermissions("blog:note:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(BlogNote note, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        if (!user.isAdmin()){
            note.setCreateBy(new User(user.getId()));
        }
        Page<BlogNote> page = blogNoteService.findPage(new Page<BlogNote>(request, response), note);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑博客文章表单页面
     */
    @RequiresPermissions(value = {"blog:note:view", "blog:note:add", "blog:note:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(BlogNote note, Model model) {
        if (note.getId() != null) {
            model.addAttribute("note", note);
        } else {
            BlogNote maxCode = blogNoteService.getMaxCode();
            model.addAttribute("note", maxCode);
        }
        return "modules/blog/note/blogNoteForm";
    }

    /**
     * 查看，增加，编辑博客文章表单页面
     */
    @RequiresPermissions(value = {"blog:note:md:view", "blog:note:md:add", "blog:note:md:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form/md")
    public String mdForm(BlogNote note, Model model) {
        if (note.getId() != null) {
            model.addAttribute("note", note);
        } else {
            BlogNote maxCode = blogNoteService.getMaxCode();
            model.addAttribute("note", maxCode);
        }
        return "modules/blog/note/blogNoteMdForm";
    }

    /**
     * 保存文章
     */
    @ResponseBody
    @RequiresPermissions(value = {"blog:note:add", "blog:note:edit", "blog:note:md:add", "blog:note:md:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(BlogNote note, Model model, RedirectAttributes redirectAttributes) throws Exception {
        AjaxJson j = new AjaxJson();
        if (!beanValidator(model, note)) {
            j.setSuccess(false);
            j.setMsg("非法参数！");
            return j;
        }

        if (blogNoteService.isExistCode(note.getCode(), note.getCreateBy())) {
            j.setSuccess(false);
            j.setMsg("文章编号已存在！");
            return j;
        }

        //新增或编辑表单保存
        blogNoteService.save(note);//保存
        j.setSuccess(true);
        j.put("note", note);
        j.setMsg("保存文章成功");
        return j;
    }

    /**
     * 删除文章
     */
    @ResponseBody
    @RequiresPermissions("blog:note:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(BlogNote note, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        blogNoteService.delete(note);
        j.setSuccess(true);
        j.setMsg("删除文章成功");
        return j;
    }

    /**
     * 批量删除文章
     */
    @ResponseBody
    @RequiresPermissions("blog:note:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            blogNoteService.delete(blogNoteService.get(id));
        }
        j.setMsg("删除文章成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("blog:note:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public AjaxJson exportFile(BlogNote note, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "博客文章" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<BlogNote> page = blogNoteService.findPage(new Page<BlogNote>(request, response, -1), note);
            new ExportExcel("博客文章", BlogNote.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出文章记录失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("blog:note:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<BlogNote> list = ei.getDataList(BlogNote.class);
            for (BlogNote note : list) {
                try {
                    blogNoteService.save(note);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条文章记录。");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条文章记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入文章失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/blog/note/?repage";
    }

    /**
     * 下载导入文章数据模板
     */
    @RequiresPermissions("blog:note:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "文章数据导入模板.xlsx";
            List<BlogNote> list = Lists.newArrayList();
            new ExportExcel("文章数据", BlogNote.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/blog/note/?repage";
    }

    /**
     * 博客图片上传
     *
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "imageUpload")
    @ResponseBody
    public EditorJson imageUpload(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "editormd-image-file", required = false) MultipartFile file) {
        EditorJson j = new EditorJson();
        User currentUser = UserUtils.getUser();
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 文件保存路径
                String realPath = Global.USERFILES_BASE_URL + currentUser.getId() + "/blog";
                // 转存文件
                FileUtils.createDirectory(Global.getUserfilesBaseDir() + realPath);
                file.transferTo(new File(Global.getUserfilesBaseDir() + realPath + "/" + file.getOriginalFilename()));
                String url = request.getContextPath() + realPath + "/" +  file.getOriginalFilename();
                logger.info("blog note url: {}", url);
                j.successJson(url);
            } catch (Exception e) {
                logger.error("blog imageUpload: ", e);
                j.errorJson(e.getMessage());
            }
        }
        return j;
    }
}
